use crate::util;
use crate::req;

const BASE_URL: &str = "http://10.0.0.55/cgi-bin/srun_portal";
const CHALLENGE_URL: &str = "http://10.0.0.55/cgi-bin/get_challenge";
const CHECK_URL: &str = "http://10.0.0.55/cgi-bin/rad_user_info";

fn refresh_challenge(username: &str) -> (String, String) {
    let retjson = req::send_req(CHALLENGE_URL, &req::gen_challenge_req(username));
    if req::check_resp(&retjson) {
        if !retjson.has_key("client_ip") {
            panic!("Bad JSON for parsing!");
        }
        let client_ip = &retjson["client_ip"];
        if !retjson.has_key("challenge") {
            panic!("Bad JSON for parsing!");
        }
        let challenge = &retjson["challenge"];
        println!("Get-Challenge succeeded.");
        println!("IP: {}", client_ip);
        println!("Challenge: {}", challenge);
        return (client_ip.to_string(), challenge.to_string());
    }
    else {
        panic!("Get-Challenge failed.");
    }
}

pub fn login(ac_id: &str, username: &str, password: &str) -> u8 {
    println!("\n\nTIME: {}", util::get_datetime());
    let (client_ip, challenge) = refresh_challenge(username);
    let retjson = req::send_req(BASE_URL, &req::gen_login_req(ac_id, username, password, &client_ip, &challenge));
    if req::check_resp(&retjson) {
        println!("Login succeeded.");
        return 0;
    }
    else {
        println!("Login failed.");
        return 1;
    }
}

pub fn logout(username: &str) -> u8 {
    println!("\n\nTIME: {}", util::get_datetime());
    let retjson = req::send_req(BASE_URL, &req::gen_logout_req(username));
    if req::check_resp(&retjson) {
        println!("Logout succeeded.");
        return 0;
    }
    else {
        println!("Logout failed.");
        return 1;
    }
}

pub fn check() -> u8 {
    println!("\n\nTIME: {}", util::get_datetime());
    let retjson = req::send_req(CHECK_URL, &req::gen_check_req());
    if retjson != json::Null {
        let error = &retjson["error"];
        match error {
            x if x.to_string() == "ok" => {
                println!("You're currently online.");
                return 0;
            },
            x if x.to_string() == "not_online_error" => {
                println!("You're not online.");
                return 1;
            },
            _ => {
                println!("Failed to check online status.");
                return 1;
            }
        }
    }
    else {
        println!("Failed to check online status.");
        return 1;
    }
}